#include "Singleton11.h"
#include <QDebug>

#include "UI/ModRun/Output/FactoryOutput.h"


//初始化成员变量;
std::mutex Singleton11::m_Mtx;
std::atomic<Singleton11*> Singleton11::m_pInstance(nullptr);

//私有化构造;
Singleton11::Singleton11()
{
    qDebug() << "C++11 单例构造";
    //防破解;
    if (m_pInstance)
    {
        throw std::runtime_error("已经实例化，不能再创建");
    }
    QString strOutput = "C++11 单例构造";
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}

Singleton11::~Singleton11()
{
    QString strOutput = "C++11 单例析构";
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}

//获取实例;
Singleton11* Singleton11::GetInstance()
{
    //获取内存中存储的值;
    Singleton11 *temp = m_pInstance.load(std::memory_order_relaxed);
    //获取内存栅栏;
    std::atomic_thread_fence(std::memory_order_acquire);
    if (nullptr == temp)
    {
        std::lock_guard<std::mutex> lock(m_Mtx);
        //获取内存中存储的值;
        temp = m_pInstance.load(std::memory_order_relaxed);
        if (nullptr == temp)
        {
            temp = new Singleton11();
            //释放内存栅格;
            std::atomic_thread_fence(std::memory_order_release);
            m_pInstance.store(temp, std::memory_order_relaxed);
        }
    }
    
    return temp;
}

//释放实例;
void Singleton11::Destory()
{
    //获取内存中存储的值;
    Singleton11* temp = m_pInstance.load(std::memory_order_relaxed);
    //获取内存栅栏;
    std::atomic_thread_fence(std::memory_order_acquire);
    if (nullptr != temp)
    {
        std::lock_guard<std::mutex> lock(m_Mtx);
        //获取内存中存储的值;
        Singleton11* temp = m_pInstance.load(std::memory_order_relaxed);
        if (nullptr != temp)
        {
            delete temp;
            temp = nullptr;
            //释放内存栅格;
            std::atomic_thread_fence(std::memory_order_release);
            m_pInstance.store(temp, std::memory_order_relaxed);
        }
    }
}

//测试函数;
void Singleton11::Display()
{
    QString strThis = QString::number(reinterpret_cast<quintptr>(this), 16);
    QString strOutput = "C++11 单例 Display " + strThis;
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}

